<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class TweetCore {

    /**
     * Get home timeline of desired user
     */
    public static function home_timeline() {
        // Get param
        $user_id  = Yii::app()->request->getParam("user_id", Yii::app()->user->id);
        $count    = Yii::app()->request->getParam("count", 20);
        $since_id = Yii::app()->request->getParam("since_id");
        $max_id   = Yii::app()->request->getParam("max_id");
        
        // Build query
        $criteria = new CDbCriteria();
        $real_tweet_id = "IF (tweet.content is null, tweet.parent_id, tweet.id)"; 
        // Basic param
        $criteria->limit = $count;
        $criteria->order = "real_tweet_id DESC";
        $criteria->addCondition("t.user_id = :user_id");
        $params = array(':user_id'  =>$user_id,);
        if ($since_id) {
            $criteria->addCondition("$real_tweet_id < :since_id");
            $params[':since_id'] = $since_id;
        }
        if ($max_id) {
            $criteria->addCondition ("$real_tweet_id > :max_id");
            $params[':max_id'] = $max_id;
        }
        $criteria->params = $params;
        
        $criteria->select = array(
            '*',
            "$real_tweet_id as real_tweet_id",
        );
        $criteria->with  = array(
            'tweet'=>array('select'=>'*'),
        );
        $criteria->group = 'real_tweet_id';
        
        // Get result
        $timelines = Timeline::model()->findAll($criteria);
        
        /*@var $tweet Tweets */
        $tweetInfos = array();
        foreach ($timelines as $timeline){
            $tweet = $timeline->tweet;
            $tweetInfo = TweetCore::getTweetInfo($tweet);
            $tweetInfos[] = $tweetInfo;
        }

        return ($tweetInfos);
    }

    /**
     * Get a tweet info
     * @param Tweets $tweet
     * @return array info
     */
    private static function getTweetInfo($tweet) {
        $retweeted_by = "";
        if (!$tweet->content) {
            if ($tweet->user->id != Yii::app()->user->id)
                $retweeted_by = $tweet->user->username;
            $tweet = $tweet->parent;
        }
        
        if (!$tweet) return;
        return array(
            'tweet_id' => $tweet->id,
            'content' => $tweet->content,
            'parent_id' => $tweet->parent_id,
            'created_time' => $tweet->created_time,
            'user_id' => $tweet->user_id,
            'username' => $tweet->user->username,
            'full_name' => $tweet->user->full_name,
            'avatar' => Html::avatarUrl($tweet->user->avatar),
            'retweeted_by' => 'luckymancvp',
            'refav' => TweetCore::calcRefav($tweet) . '',
        );
    }

    private static function calcRefav($tweet){
        $refav = 0;
        if (Tweets::model()->findByAttributes(
                array(
                    'parent_id'=>$tweet->id,
                    'user_id'  =>Yii::app()->user->id, 
                    'content'  =>null,
                ),
                array(
                    'select'=>'id',
                )
        )) $refav++;
        if (Favorites::model()->findByAttributes(
                array('user_id'=>Yii::app()->user->id, 'tweet_id'=>$tweet->id),
                array(
                    'select'=>'id',
                )
        )) $refav+=10;
        return $refav;
                
    }

    public static function show($user_id) {
        $login_id = Yii::app()->user->id;
        $follow_status = 0;

        if ($user_id != $login_id) {
            if (Follows::model()->exists('user_id = :user_id AND follow_id = :follow_id', array('user_id' => Yii::app()->user->id, 'follow_id' => $user_id))) {
                $follow_status = 1;
            }
        }

        // Query user info
        $user_info = Yii::app()->db->createCommand()
                ->select('u.id AS user_id, u.username, u.full_name, CONCAT(:path, u.avatar) AS avatar, u.location, u.website, u.bio, t.tweets_count, f1.following_count, f2.followers_count')
                ->from('users AS u')
                ->leftJoin('(SELECT user_id, COUNT(id) AS tweets_count FROM tweets WHERE user_id = :user_id) AS t', 't.user_id = u.id')
                ->leftJoin('(SELECT user_id AS id, COUNT(follow_id) AS following_count FROM follows WHERE user_id = :user_id) AS f1', 'f1.id = u.id')
                ->leftJoin('(SELECT follow_id AS id, COUNT(user_id) AS followers_count FROM follows WHERE follow_id = :user_id) AS f2', 'f2.id = u.id')
                ->where('u.id = :user_id')
                ->limit(1)
                ->queryRow(true, array('user_id' => $user_id, 'path' => Yii::app()->createAbsoluteUrl('avatars') . '/'));

        if (isset($user_info)) {
            $user_info['follow_status'] = $follow_status;
        } else {
            $user_info['follow_status'] = null;
        }
        return $user_info;      
    }
    
    /**
     * Get user timeline of desired user
     */
    public static function user_timeline($user_id){
        $t = microtime(true);
        // Get param
        $count    = Yii::app()->request->getParam("count", 20);
        $since_id = Yii::app()->request->getParam("since_id");
        $max_id   = Yii::app()->request->getParam("max_id");
        
        // Build query
        $criteria = new CDbCriteria();
        $real_tweet_id = "IF (t.content is null, t.parent_id, t.id)"; 
        $criteria->select = array('*', "$real_tweet_id as real_tweet_id");
        $criteria->limit = $count;
        $criteria->order = "real_tweet_id DESC";
        $criteria->group = "real_tweet_id";
        $criteria->addCondition("user_id = :user_id");
        $params = array(':user_id'  =>$user_id,);
        if ($since_id) {
            $criteria->addCondition("$real_tweet_id < :since_id");
            $params[':since_id'] = $since_id;
        }
        if ($max_id) {
            $criteria->addCondition ("$real_tweet_id > :max_id");
            $params[':max_id'] = $max_id;
        }
        $criteria->params = $params;
        
        // Get result
        $tweets = Tweets::model()->findAll($criteria);
        
        /*@var $tweet Tweets */
        $tweetInfos = array();
        foreach ($tweets as $tweet){
            $tweetInfo = TweetCore::getTweetInfo($tweet);
            $tweetInfos[] = $tweetInfo;
        }
        
        return ($tweetInfos);
    }

}

?>
